<?php

namespace Biz\module\Classes\mgt;

use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderRefund as mOrderRefund;
use Biz\model\trade\OrderActivityLog as mOrderActivityLog;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\service\trade\Order as sOrder;
use Biz\service\trade\Logistics as sLogistics;
use Biz\tools\Amount;
use Doraemon\service\User as sUser;
use Biz\tools\OrderNo as toolOrderNo;
use Biz\module\Classes\Order as clsOrder;
use Biz\module\Classes\OrderInfo as clsOrderInfo;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\model\trade\ShopCourier as mShopCourier;
use Biz\service\activity\PinTuan as sPinTuan;
use Biz\service\redPacket\RedPacketsLog as sRedPacketsLog;
use Biz\model\trade\OrderMatching as mOrderMatching;
use Biz\model\trade\OrderPackage as mOrderPackage;

class OrderDetail
{
    private $orderTime = []; //存放格式化的订单时间组

    private $timeDesc = [ //订单时间对应描述label
        'addtime' => '下单时间',
        'pay_time' => '支付时间',
        'paystop_time' => '最终支付时间',
        'delivery_time' => '发货时间',
        'confirm_time' => '成交时间', //收货时间
        'autoconfirm_time' => '自动确认收货时间',
        'prolong_time' => '延长时间',
        'cancel_time' => '取消时间',
        'edittime' => '编辑时间'
    ];

    public function getInfo($shopId, $orderNo)
    {
        $result = [];

        //判断是否父订单
        if (toolOrderNo::isParentNo($orderNo)) {
            throw new \Exception('父订单号不支持商家查看', 0);
        }

        //获取订单信息
        $orderInfo = mOrder::getOrderInfoFromMaster($orderNo);

        if (empty($orderNo) || empty($orderInfo)) {
            throw new \Exception('抱歉，该订单不存在', 0);
        }

        if ($orderInfo['shop_id'] != $shopId) {
            throw new \Exception('抱歉，您非正常查看订单', 0);
        }

        //查询orderGoods字段
        $fields = [
            'order_no',
            'cover_img',
            'title',
            'sell_price',
            'buy_price',
            'buy_num',
             'sku_desc',
            'sku_id',
            'discount_amount',
            'goods_amount',
            's_coupon_id',
            's_coupon_amount',
            'pay_amount',
            'promo_type',
            'promo_id',
            'meal_id',
            'meal_amount',
            'activity_allowance',
            'reserve_receipt_time'
        ];

        $orderGoods = mOrderGoods::getFieldsByOrderNo($orderNo, $fields);

        $refundList=mOrderRefund::getRefundListByOrderNoForMgtDetailAndList($orderNo);
//var_dump($refundList);die;

        foreach ($orderGoods as &$orderGood) {
            $orderGood['refund_order_no']=$refundList[$orderNo][$orderGood['sku_id']]['refund_order_no'];
            $orderGood['refund_status']=$refundList[$orderNo][$orderGood['sku_id']]['status'];
            $orderGood['refund_status_desc']=$refundList[$orderNo][$orderGood['sku_id']]['status_desc'];
            $orderGood['rights_status']=$refundList[$orderNo][$orderGood['sku_id']]['rights_status'];
            $orderGood['rights_status_desc']=$refundList[$orderNo][$orderGood['sku_id']]['rights_status_desc'];
            $orderGood['rights_process_method']=$refundList[$orderNo][$orderGood['sku_id']]['rights_process_method'];
            $orderGood['type_refund']=$refundList[$orderNo][$orderGood['sku_id']]['type_refund'];
            $orderGood['promo_type_desc'] = ActivityInfo::ACTIVITY_TYPES_MAPS[$orderGood['promo_type']];
            $orderGood['status'] = $orderInfo['status'];
            $orderGood['status_desc'] = mOrder::$statusMgtDesc[$orderInfo['status']];
            $orderGood['cover_img'] = $orderGood['cover_img_thumb_url'];
            $orderGood['goods_amount'] = $orderGood['goods_amount']-$orderGood['meal_amount'];
            $orderGood['reserve_receipt_time'] = strtotime(date('Y-m-d H:i:s',$orderGood['reserve_receipt_time']))>0?$orderGood['reserve_receipt_time']:'';

            //是否参与活动
            if( $orderGood['promo_type'] > 0 ){
                $activitys[$orderGood['promo_type']][] = $orderGood['order_no'];
            }
        }

        if(isset($activitys)){
            $activity = self::getActivity($activitys, $orderGoods);
        }

        //处理数据返回
        $result['order_no'] = $orderNo;
        $result['nick'] = sUser::getUser($orderInfo['uid'])['nick'];

        //收货人
        $result['accept_info'] = [
            'uid' => $orderInfo['uid'],
            'consignee_name' => $orderInfo['consignee_name'],
            'consignee_phone' => $orderInfo['consignee_phone'],
            'consignee_address' => $orderInfo['consignee_address'],
            'consignee_info_address' => $orderInfo['consignee_info_address'],
            'consignee_code' => [
                $orderInfo['consignee_province'],
                $orderInfo['consignee_city'],
                $orderInfo['consignee_area']
            ]
        ];

        //获取收货地址详情
        $orderMatch = mOrderMatching::getInfo($orderNo);
        if(!empty($orderMatch)){
            $orderMatch =  current($orderMatch);
            $result['accept_info']['is_inter_community'] = $orderMatch['is_inter_community'];
            $result['accept_info']['is_has_elevator'] = $orderMatch['is_has_elevator'];
            $result['accept_info']['which_floor'] = $orderMatch['which_floor']??0;
        }

        //买家留言
        $result['message'] = $orderInfo['message'];

        $orderRemarks = sOrder::OrderRemarks([$orderNo]);
        //商家备注
        $result['seller_message'] = $orderRemarks[$orderNo]['seller_messages'];
		$result['seller_message_addtime'] = $orderRemarks[$orderNo]['seller_message_time'];
		//好好住备注
		$result['hhz_message'] = $orderRemarks[$orderNo]['hhz_message'];


        //订单时间组
        $formatTime = [
            'addtime' => $orderInfo['addtime'], //下单时间
            'pay_time' => $orderInfo['pay_time'], //支付时间
            'delivery_time' => $orderInfo['delivery_time'], //发货时间
            'confirm_time' => $orderInfo['confirm_time'], //收货时间（成交时间）
        ];
        $this->getFormatOrderTime($formatTime);
        $result['time_info'] = $this->orderTime;


        //订单状态
        $result['status'] = $orderInfo['status'];
        $result['status_desc'] = mOrder::$statusMgtDesc[$orderInfo['status']];

        //是否分单发货
        $result['is_package_delivery'] = $orderInfo['is_package_delivery'];

        //物流信息
        $result['delivery_tracking'] = clsOrderInfo::getOrderDeliveryTracking($orderNo,$orderInfo);

        //积分抵扣金额
        $result['integral_amount'] = $orderInfo['integral_amount'];

        //优惠券抵扣金额
        $result['coupon_amount'] = $orderInfo['coupon_amount'];

        //活动补贴
        $result['activity_allowance'] = $orderInfo['activity_allowance'];

        //店铺优惠券抵扣
        $result['s_coupon_amount'] = $orderInfo['s_coupon_amount'];

        //套餐优惠信息
        $result['meal_id'] = $orderInfo['meal_id'];

        //订单实际付款
        $result['pay_amount'] = $orderInfo['pay_amount'];

        //运费  订单金额
        $result['shipping_amount'] = $orderInfo['shipping_amount'];
        $result['goods_amount'] = $orderInfo['goods_amount'];
        $result['order_amount'] = Amount::format($result['shipping_amount'] + $result['goods_amount']);

        //订单使用红包金额
        $result['red_packet'] = !empty(sRedPacketsLog::getInfo($orderNo))?sRedPacketsLog::getInfo($orderNo):'0.00';

        //商品详情
        $result['goods_info'] = $orderGoods;

        //参与的活动信息
        if(isset($activity) && !empty($activity)){
            foreach($activity as $_ak=>&$_av) {
                if (isset($_av[$orderNo])) {
                    $result[$_ak] = $_av[$orderNo];
                }
            }
        }

        $orderPackage = mOrderPackage::getFirstPackageInfo($orderNo);

        //加上courierid
        $courierInfo = mShopCourier::getCourier(['courier_id'],['courier_name'=>$orderPackage['express_company']]);

        $result['courier_id'] = isset($courierInfo['courier_id'])?$courierInfo['courier_id']:0;

        return $result;
    }

    private static function getActivity($activity, $skuList){
        $data = [];
        foreach(ActivityInfo::ACTIVITY_TYPES_MAPS as $_k=>$_v) {
            switch ($_k) {
                case ActivityInfo::ACTIVITY_TYPE_PINTUAN;
                    $data = sPinTuan::getSkuOrder($activity[ActivityInfo::ACTIVITY_TYPE_PINTUAN], $skuList);
                    break;
            }
        }
        return $data;
    }

    public function getFormatOrderTime($orderTimes = [])
    {
        foreach ($orderTimes as $key => $value) {
            if ($value != '0000-00-00 00:00:00') {
                $this->orderTime[] = [
                    'label' => $this->timeDesc[$key],
                    'time' => $value
                ];
            }
        }
    }

}
